package servlets;

import java.io.IOException;

import javaPersistence.Client;
import javaPersistence.Producto;
import javaPersistence.SaleService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.FormData;

/**
 * Servlet implementation class LoadDataSales
 */
@WebServlet("/LoadSales")
public class LoadDataSales extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoadDataSales() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String clienteCode = "";
		int productCode = 0;
		double cantSale = 0d;
		FormData fdata = new FormData();	
		try {
			HttpSession sess = request.getSession();
			SaleService saleServ = new SaleService();
			Client client = new Client();
			Producto product = new Producto();
			clienteCode = request.getParameter("clienteCode");
			productCode = Integer.parseInt(request.getParameter("productCode"));
			cantSale = Double.parseDouble(request.getParameter("cantSale"));
			if(clienteCode != null && productCode > 0 && cantSale > 0){
				int userCed = Integer.parseInt(sess.getAttribute("userCode").toString());
				if(!saleServ.insertSaleService(userCed, clienteCode, productCode, cantSale)){
					fdata.setError("Error: Los datos insertados ya existen o estan mal diligenciados.");
				}else{
					fdata.setMsgOK("OK: Los datos fueron almacenados correctamente.");
					fdata.setClients(client.loadAllClient());
					fdata.setServices(product.loadAllServices());
					fdata.setSaleServices(saleServ.loadAllDataSalesServices());
				}
			}else{
				fdata.setError("TODOS: Los datos son necesarios");
			}
			sess.setAttribute("FormData", fdata);
			response.sendRedirect(request.getContextPath() + "/jsps/negocio/ventas.jsp");
		} catch (Exception e) {
			fdata.setError("Error: Los datos insertados ya existen o estan mal diligenciados.");
		}
	}

}
